package com.zwb.service.controller;

import com.zwb.service.common.CacheConstant;
import com.zwb.service.dto.AdminRoleDto;
import com.zwb.service.enums.StatusCode;
import com.zwb.service.pojo.Admin;
import com.zwb.service.pojo.Role;
import com.zwb.service.service.IAdminRoleService;
import com.zwb.service.service.IAdminService;
import com.zwb.service.service.IRoleService;
import com.zwb.service.vo.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 头发又黑又长
 * @Date 2022/9/6 19:18
 * @email zwb15083976291@163.com
 */
@Api(tags = "操作员管理")
@RestController
@RequestMapping("/system/admin")
public class AdminController {

    @Autowired
    private IAdminService adminService;

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IAdminRoleService adminRoleService;

    @ApiOperation("获取所有操作员")
    @GetMapping("/")
    public R<List<Admin>> getAllAdmins(String keywords) {
        if (keywords.length() < 1) {
            return R.result(StatusCode.VALID_ERROR);
        }
        List<Admin> admins = adminService.getAllAdmins(keywords);
        return R.success(admins);
    }


    @ApiOperation("更新操作员")
    @PostMapping("/")
    public R updateAdmin(@RequestBody Admin admin) {
        if (ObjectUtils.isEmpty(admin.isEnabled())) {
            Admin currentAdmin = adminService.getById(admin);
            // 给 enabled 赋值
            admin.setEnabled(currentAdmin.isEnabled());
        }
        return adminService.updateById(admin) ?
                R.success("更新操作员成功") : R.error("更新操作员失败");
    }

    @ApiOperation("删除操作员")
    @DeleteMapping("/{id}")
    public R deleteAdmin(@PathVariable("id") Integer id) {
        return adminService.removeById(id) ?
                R.success("删除操作员成功") : R.error("删除操作员失败");
    }

    @ApiOperation("获取所有角色")
    @GetMapping("/roles")
    public R<List<Role>> getAllRoles() {
        return R.success(roleService.list());
    }


    @ApiOperation("更新操作员角色信息")
    @PostMapping("/role")
    public R updateAdminRoles(@RequestBody AdminRoleDto adminRoleDto) {
        adminRoleService.updateAdminRoles(adminRoleDto);
        return R.success("更新操作员角色成功");
    }
}
